﻿using Project.DAL;
using Project.DAL.GoodsDal;
using Project.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project.BLL.GoodsBll
{
    public class GoodsBll : BaseBLL<Goods>
    {
        public override void SetDal()
        {
            Dal = new GoodsDal();
        }

        //分页显示商品
        public List<Goods> GetGoodsByPage(int page, int size, out int count, string name) {
            var data = base.Query();
            if (!string.IsNullOrWhiteSpace(name)) {
              data=data.Where(x => x.name.Contains(name));
            }
            count = data.Count();
            data = data.OrderBy(x => x.gId).Skip((page - 1) * size).Take(size);
            return data.ToList();
        }
        public bool DelGoods(int gid) {
            var data = base.Query().Where(x => x.gId == gid).FirstOrDefault();
            var kdal = new GoodsPropertyKeyDal();
            var vdal = new GoodsPropertyValueDal();
            foreach (var key in data.GoodsPropertyKey)
            {
                vdal.Delete(key.GoodsPropertyValue.ToList());
            }

            var keys = data.GoodsPropertyKey;
            kdal.Delete(keys.ToList());
            Dal.Delete(data);
            return Dal.SaveChanges();
        }
        public bool UpdateGood(Goods good)
        {
            var data = base.Query().Where(g => g.gId == good.gId).FirstOrDefault();

            //1. 修改商品信息信息表
            data.name = good.name;
            data.price = good.price;
            data.unit = good.unit;
            data.gtId = good.gtId;
            data.use_property = good.use_property;
            data.use_spec = false;
            data.content = good.content;
            data.images = good.images;
            data.sort = good.sort;

            var kdal = new GoodsPropertyKeyDal();
            var vdal = new GoodsPropertyValueDal();

            //2. 删除旧 values
            foreach (var key in data.GoodsPropertyKey)
            {
                vdal.Delete(key.GoodsPropertyValue.ToList());
            }

            //3. 删除旧的 keys
            var keys = data.GoodsPropertyKey;
            kdal.Delete(keys.ToList());



            //4. 添加新的key value
            kdal.Add(good.GoodsPropertyKey.ToList());

            //5. 修改数据
            Dal.Update(data);

            //6. 保存修改
            return Dal.SaveChanges();
        }
    }
}
